package com.fu.plugin.trees;

import com.fu.plugin.trees.nodes.MyTreeNode;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.impl.java.stubs.index.JavaAnnotationIndex;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.ui.treeStructure.SimpleNode;
import com.intellij.ui.treeStructure.SimpleTreeStructure;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.List;

public class MyTreeStructure extends SimpleTreeStructure {
    private MyTreeNode root;

    public MyTreeStructure(Project project){
        root = new MyTreeNode(project.getName(), null, null);
        Module[] modules = ModuleManager.getInstance(project).getModules();
        if(modules != null && modules.length > 0){
            List<MyTreeNode> children = root.children();
            for(Module module: modules){
                MyTreeNode moduleNode = new MyTreeNode(module.getName(), root, null);
                List<MyTreeNode> moduleChild = moduleNode.children();
                children.add(moduleNode);

                Collection<PsiAnnotation> controller = JavaAnnotationIndex.getInstance().get("Controller", project, GlobalSearchScope.moduleScope(module));

                if(null != controller && controller.size() > 0){
                    for(PsiAnnotation psiAnnotation : controller){
                        PsiClass psiClass = (PsiClass) psiAnnotation.getParent().getParent();
                        PsiMethod[] methods = psiClass.getMethods();
                        if(null != methods && methods.length > 0){
                            for(PsiMethod method : methods){
                                moduleChild.add(new MyTreeNode(method.getName(), moduleNode, method));
                            }
                        }
                    }
                }
            }
        }
    }

    @NotNull
    @Override
    public Object getRootElement() {
        return root;
    }

    public SimpleNode getRoot(){
        return root;
    }
}
